package com.am.meeting.service.impl;
import com.am.api.client.FileClient;
import com.am.api.dto.MeetingFileDto;
import com.am.common.exception.DbException;
import com.am.common.utils.BeanUtils;
import com.am.common.utils.UserContext;
import com.am.meeting.domain.Result;
import com.am.meeting.domain.dto.MeetRecordDto;
import com.am.meeting.domain.po.MeetingTags;
import com.am.meeting.domain.po.Meetingrecord;
import com.am.meeting.domain.po.Tags;
import com.am.meeting.domain.po.UserMeeting;
import com.am.meeting.domain.vo.MeetingRecordVO;
import com.am.meeting.enums.MeetingStatus;
import com.am.meeting.mapper.MeetingTagsMapper;
import com.am.meeting.mapper.MeetingrecordMapper;
import com.am.meeting.mapper.TagsMapper;
import com.am.meeting.mapper.UserMeetingMapper;
import com.am.meeting.service.IMeetingrecordService;
import com.am.meeting.utils.MeetingNumberGenerator;
import com.am.meeting.utils.TagsStringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.lettuce.core.ScriptOutputType;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cq
 * @since 2025-02-01
 */
@Slf4j
@Service
public class MeetingrecordServiceImpl extends ServiceImpl<MeetingrecordMapper, Meetingrecord> implements IMeetingrecordService {
@Autowired
MeetingrecordMapper meetingrecordMapper;
@Autowired
TagsMapper tagsMapper;
@Autowired
MeetingTagsMapper meetingTagsMapper;
@Autowired
MeetingTagsServiceImpl meetingTagsService ;
@Autowired
    UserMeetingMapper userMeetingMapper;
@Autowired
FileClient fileClient;
@Autowired
    MeetingNumberGenerator meetingNumberGenerator;
    /**
     *
     *   meetingrecord.setUserId(111l);
     *   meetingrecord.setMeetingNumber("1231");
     *   登录id获取
     *   会议号设计
     * @param meetRecordDto
     * @return
     */

    @Override
    public Result creatMeeting(MeetRecordDto meetRecordDto) throws SQLException {

        //会议信息保存
        Meetingrecord meetingrecord = new Meetingrecord();
        String[] tags = meetRecordDto.getTags();

        Long userId=111l;
        if(UserContext.getUser()!=null) {
            userId = UserContext.getUser();
        }
        String s = TagsStringUtils.combineArrayToString(tags);
        meetingrecord.setTags(s);
        meetingrecord.setMeetingServe(meetRecordDto.getCatering());
        meetingrecord.setMeetingAddress(meetRecordDto.getLocation());
        meetingrecord.setMeetingRule(meetRecordDto.getRules());
        meetingrecord.setMeetingDuration(meetRecordDto.getDuration());
        meetingrecord.setMeetingTheme(meetRecordDto.getTitle());
        meetingrecord.setMeetingType(meetRecordDto.getParticipationMode());
        meetingrecord.setMeetingStarttime(meetRecordDto.getStartTime());

        meetingrecord.setUserId(userId);


        String meetingNum=meetingNumberGenerator.generateMeetingNumber();

        //确保会议号唯一
        meetingNum= meetingNumberGenerator.generateMeetingNumber();
        meetingrecord.setMeetingNumber(meetingNum);

        try {
            int insert = meetingrecordMapper.insert(meetingrecord);
//用户会议关系
            UserMeeting userMeeting = new UserMeeting();
            userMeeting.setUserId(userId);
            userMeeting.setMeetingId(meetingrecord.getId());
            userMeeting.setType(true);
            userMeetingMapper.insert(userMeeting);
//会议标签信息保存

            QueryWrapper<Tags> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("name", tags);
            List<Tags> tagList = tagsMapper.selectList(queryWrapper);

            // 构建标签名到标签对象的映射
            Map<String, Tags> tagMap = new HashMap<>();
            for (Tags tag : tagList) {
                tagMap.put(tag.getName(), tag);
            }

            // 准备批量插入的数据
            List<MeetingTags> meetingTagsList = new ArrayList<>();
            for (String tagName : tags) {
                Tags tag = tagMap.get(tagName);
                if (tag != null) {
                    meetingTagsList.add(new MeetingTags(null, tag.getId(), meetingrecord.getId()));
                }
            }
            // 批量插入关联数据
            if (!meetingTagsList.isEmpty()) {
                meetingTagsService.saveBatch(meetingTagsList);
            }
//会议材料信息保存
            String[] meetingMaterials = meetRecordDto.getMeetingMaterials();
            List<MeetingFileDto> meetingFileDtos = new ArrayList<>();
            for (String meetingMaterial : meetingMaterials) {
                String[] split = meetingMaterial.split("/");
                String filename=new String(meetingMaterial);
                if(split.length>0){
                    filename=split[split.length-1];
                }
                MeetingFileDto meetingFileDto = new MeetingFileDto(meetingrecord.getId(),filename,meetingMaterial,null);
                meetingFileDtos.add(meetingFileDto);
            }
            Collection<Long> longs = fileClient.saveFile(meetingFileDtos);

            if ((insert>0)) {
                return Result.success();
            }else
            {
                return Result.error("creating error");
            }
        }catch (DbException dbException){
            throw new SQLException(dbException.getMessage());
           // return Result.error("SqlException！！");
        }
        }

    @Override
    public Result fingJoinMeeting() throws SQLException {
Long userid=111l;
        if(UserContext.getUser()!=null) {
            userid = UserContext.getUser();
        }
        // 查询当前用户参加的所有 UserMeeting 记录
        List<UserMeeting> userMeetings = userMeetingMapper.selectList(new QueryWrapper<UserMeeting>().eq("user_id",userid));
        // 提取会议 ID 列表
        List<Long> meetingIds = new ArrayList<>();
        for (UserMeeting userMeeting : userMeetings) {
            meetingIds.add(userMeeting.getMeetingId());
        }
        // 批量查询会议记录
        if (!meetingIds.isEmpty()) {
            System.out.println(meetingIds);
            ArrayList<MeetingRecordVO> meetingRecordVOS = new ArrayList<>();
            List<Meetingrecord> meetingrecords = meetingrecordMapper.selectBatchIds(meetingIds);

            System.out.println(meetingrecords);
            for (Meetingrecord meetingrecord : meetingrecords) {
                MeetingRecordVO meetingRecordVO = new MeetingRecordVO();
                meetingRecordVO.setMeetingId(meetingrecord.getId());
                meetingRecordVO.setMeetNum(meetingrecord.getMeetingNumber());
                meetingRecordVO.setTitile(meetingrecord.getMeetingTheme());
                meetingRecordVO.setStartTime(meetingrecord.getMeetingStarttime());
                meetingRecordVO.setUserId(meetingrecord.getUserId());
                //计算会议开始结算时间用来判断当前会议状态
                LocalDateTime meetingStarttime = meetingrecord.getMeetingStarttime();
                System.out.println(meetingrecord.getMeetingDuration());
                LocalDateTime meetingOvertime=meetingStarttime.plusMinutes(meetingrecord.getMeetingDuration());
                MeetingStatus start;
              if (LocalDateTime.now().isBefore(meetingStarttime)){
                  start = MeetingStatus.NOT_START;
              }else if(LocalDateTime.now().isBefore(meetingOvertime)||LocalDateTime.now().isEqual(meetingStarttime)) {
                  start = MeetingStatus.STARTING;
              }else {
                  start=MeetingStatus.OVER;
              }
              meetingRecordVO.setMeetingState(start.getValue());
                meetingRecordVOS.add(meetingRecordVO);
            }
          return Result.success(meetingRecordVOS);
        }else {
            return Result.success(null);
        }
    }

    /**
     * 加入会议
     * @return
     * @throws SQLException
     */
    @Override
    public Result jionByNumber(Long Number) throws SQLException {
        Long userid=111l;
        if(UserContext.getUser()!=null) {
            userid = UserContext.getUser();
        }
        Meetingrecord meeting_number = meetingrecordMapper.selectOne(new QueryWrapper<Meetingrecord>().eq("meeting_number", Number));

        if(meeting_number==null)
        {
            return Result.error("会议号不存在");
        }
        UserMeeting userMeeting = new UserMeeting();
        userMeeting.setMeetingId(meeting_number.getId());
        userMeeting.setUserId(userid);
        userMeeting.setType(false);
        int insert=0;
        try {
            UserMeeting userMeeting1 = userMeetingMapper.selectOne(new QueryWrapper<UserMeeting>().eq("meeting_id", userMeeting.getMeetingId()).eq("user_id", userid));
            if(userMeeting1==null) {
                insert = userMeetingMapper.insert(userMeeting);
                return Result.success("加入成功");
            }else{
                return Result.error("重复加入");
            }
        }catch (DbException dbException){
            throw new DbException("保存错误");
        }finally {
            if(insert==0) {
                Result.error("加入失败");
            }
        }

    }

    @Override
    public Result quitByMeetingid(Long meetingId) {
        UserMeeting userMeeting = new UserMeeting();
        Long userid=112l;
        if(UserContext.getUser()!=null) {
            userid = UserContext.getUser();
        }
        try {
            userMeeting.setMeetingId(meetingId);
            userMeeting.setUserId(userid);
            UserMeeting uM = userMeetingMapper.selectOne(new QueryWrapper<>(userMeeting));
            if(uM!=null&&uM.getType()){
                return Result.error("主办方无法退出会议");
            }else {
                userMeetingMapper.deleteById(uM.getId());
                return Result.success("退出成功");
            }
        }catch (Exception e){
            return Result.error("已经退出");
        }

    }
}